package com.jhgsys.internal.sypq.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.jhgsys.internal.dict.service.IDictService;
import com.jhgsys.internal.sypq.entity.Resource;
import com.jhgsys.internal.sypq.entity.Task;
import com.jhgsys.internal.sypq.mapper.ResourceMapper;
import com.jhgsys.internal.sypq.mapper.TaskMapper;
import com.jhgsys.internal.sypq.service.IResourceService;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.sypq.service.ITaskService;
import com.jhgsys.internal.system.entity.User;
import com.jhgsys.internal.system.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import com.jhgsys.internal.common.entity.FebsConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.StringPool;

import java.util.*;

/**
 *  Service实现
 *
 * @author ganjun
 * @date 2024-11-10 20:12:58
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements IResourceService {

    @Autowired
    private IUserService userService;

    @javax.annotation.Resource
    private IDictService dictService;

    @javax.annotation.Resource
    private TaskMapper taskMapper;

    /**
     * 查询（分页）
     * @author ganjun
     * @date 2024-11-10 20:12:58
     * @param request QueryRequest
     * @param resource resource
     * @return IPage<Resource>
    */
    @Override
    public IPage<Resource> findResourcePage(QueryRequest request, String name, String rsPlace) {
        LambdaQueryWrapper<Resource> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Resource::getDeletedFlg, 0);
        //名称模糊查询
        if(StringUtils.isNotEmpty(name)){
            queryWrapper.like(Resource::getRsName, name);
        }
        //所属场所查询
        if(StringUtils.isNotEmpty(rsPlace)){
            queryWrapper.like(Resource::getRsPlace, rsPlace);
        }
        queryWrapper.orderByDesc(Resource::getCreatedTime);
        Page<Resource> page = new Page<>(request.getPageNum(), request.getPageSize());
        FebsUtil.pageWrapper(page, request);
        IPage<Resource> iPage = this.page(page, queryWrapper);
        List<Resource> rsList = iPage.getRecords();
        if(CollectionUtil.isNotEmpty(rsList)){
            for(Resource rs : rsList){
                String rsId = rs.getId();
                LambdaQueryWrapper<Task> taskQueryWrapper = new LambdaQueryWrapper<>();
                taskQueryWrapper.eq(Task::getRsid, rs.getId());
                taskQueryWrapper.eq(Task::getStatus, 5);
                taskQueryWrapper.eq(Task::getDeletedFlg, 0);
                List<Task> taskList = taskMapper.selectList(taskQueryWrapper);
                if(CollectionUtil.isNotEmpty(taskList) && taskList.size() > 0){
                    rs.setRsStatus(1);
                    rs.setRsStatusName("占用");
                }
            }
        }
        iPage.setRecords(rsList);
        return iPage;
    }

    @Override
    public List<Resource> export(QueryRequest request, String name, String rsPlace) {
        LambdaQueryWrapper<Resource> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Resource::getDeletedFlg, 0);
        //名称模糊查询
        if(StringUtils.isNotEmpty(name)){
            queryWrapper.like(Resource::getRsName, name);
        }
        //所属场所查询
        if(StringUtils.isNotEmpty(rsPlace)){
            queryWrapper.like(Resource::getRsPlace, rsPlace);
        }
        queryWrapper.orderByDesc(Resource::getCreatedTime);
        return this.baseMapper.selectList(queryWrapper);
    }

    /**
     * 查询（所有）
     * @author ganjun
     * @date 2024-11-10 20:12:58
     * @param resource resource
     * @return List<Resource>
     */
    @Override
    public List<Resource> findResourceList(Resource resource) {
	    LambdaQueryWrapper<Resource> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Resource::getDeletedFlg, 0);
		// TODO 设置查询条件
		return this.baseMapper.selectList(queryWrapper);
    }

    /**
    * 根据ID查询
    * @author ganjun
    * @date 2024-11-10 20:12:58
    * @param id
    * @return Resource
    */
    @Override
    public Resource findResourceById(String id){
        return this.baseMapper.selectById(id);
    }

    /**
     * 新增
     * @author ganjun
     * @date 2024-11-10 20:12:58
     * @param resource resource
     */
    @Override
    @Transactional
    public boolean createResource(Resource resource) {
        resource.setDeletedFlg("0");
        resource.setRsStatus(3);
        resource.setRsStatusName(dictService.findDictLabel("RS_STATUS", "3"));
        return this.save(resource);
    }

    /**
     * 修改
     * @author ganjun
     * @date 2024-11-10 20:12:58
     * @param resource resource
     */
    @Override
    @Transactional
    public boolean updateResource(Resource resource) {
        return this.updateById(resource);
    }

    /**
     * 逻辑删除
     * @author ganjun
     * @date 2024-11-10 20:12:58
     * @param resource resource
     * @param resourceIds resourceIds
     */
    @Override
    @Transactional
    public boolean deleteResource(Resource resource,String resourceIds) {
        boolean result = false;
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        List<String> list = Arrays.asList(resourceIds.split(StringPool.COMMA));

        resource.setDeletedBy(user.getUserName());
        resource.setDeletedTime(new Date());
        resource.setDeletedFlg(FebsConstant.INVALID);
        int update = this.baseMapper.update(resource,new LambdaQueryWrapper<Resource>().in(Resource::getId,list));
        if (update > 0 ){
            result = true;
        }
        return result;
	}

    /**
    * 物理删除
    * @author ganjun
    * @date 2024-11-10 20:12:58
    * @param resourceIds resourceIds
    */
    @Override
    @Transactional
    public boolean physicallyDeleteResource(String resourceIds) {
        List<String> list = Arrays.asList(resourceIds.split(StringPool.COMMA));
        LambdaQueryWrapper<Resource> wapper = new LambdaQueryWrapper<>();
        wapper.in(Resource::getId,list);
        return this.remove(wapper);
    }


    /**
     * 根据角色获取用户
     * @return
     */
    @Override
    public List<User> getUsersByRoleId(){
        List<User> userByRole = userService.findByRoleId("c2331034b20a380bf860b331cdd12619", "0");
        return userByRole;
    }

    @Override
    public List<User> getUsersByTenantId(String tenantId){
        User user = new User();
        user.setTenantId(tenantId);
        List<User> users = userService.findUserList(user);
        return users;
    }
}
